package com.key.realm;

import com.key.entity.SysMenu;
import com.key.entity.SysRole;
import com.key.entity.SysUser;
import com.key.mapper.SysMenuMapper;
import com.key.mapper.SysRoleMapper;
import com.key.mapper.SysUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("==进入授权方法==");
        //根据账户名查询系统用户信息
        String userName =  String.valueOf(principalCollection.getPrimaryPrincipal());
        SysUser sysUser = sysUserMapper.findSysUerByUserName(userName);
        List<SysRole> sysRoleList = sysRoleMapper.findSysRoleByUserId(sysUser.getUserId());

        if(sysRoleList.size() > 0){
            List<Integer> rIds=new ArrayList<>();
            //遍历去重
            Set<String> roleSets = new HashSet<>();
            for (SysRole r:sysRoleList) {
                roleSets.add(r.getRoleTitle());
                rIds.add(r.getRoleId());
            }
            List<SysMenu> menus = sysMenuMapper.findMenuByRIds(rIds);
            Set<String> menuSets = new HashSet<>();
            for (SysMenu menu : menus) {
                menuSets.add(menu.getMenuName());
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //授权
            info.setRoles(roleSets);
            info.setStringPermissions(menuSets);
            System.out.println(info);
            return info;
        }
        return null;
    }

    //认证:将客户端传递过来的账户密码 与 数据库中获取的账户密码进行比较
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("====认证方法====");
        String userName = String.valueOf(authenticationToken.getPrincipal());
        SysUser sysUser = sysUserMapper.findSysUerByUserName(userName);
        if (sysUser!=null){
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(sysUser.getUserName(),sysUser.getUserPassword(),"myRealm");
            info.setCredentialsSalt(ByteSource.Util.bytes("gxa"));

            return info;
        }
        return null;
    }
}
